package brushQuestions.lru;

import lombok.Data;

import java.util.LinkedHashMap;

/**
 * LRU淘汰算法实现
 *
 * @author: mengfanbing
 * @date: 2020/6/6 12:47
 */
@Data
public class LruCache<K,V> {

    private LinkedHashMap<K,V> linkedHashMap;

    private int initSize;

    LruCache(Integer initSize){
        linkedHashMap = new LinkedHashMap<K,V>(16,0.75F,true);
        this.initSize = initSize;
    }

    /*public boolean rmOldestElement(){
        if ()
    }*/

    //判断是否达到了指定大小
    public boolean judle(){
        if (linkedHashMap.size() >= initSize){
            return true;
        }
        return false;
    }

    //新增元素
    public boolean put(K k,V v){
        try{
            if (this.judle()){
                linkedHashMap.remove(linkedHashMap.values().toArray()[0]);
            }
            linkedHashMap.put(k,v);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    //根据key获取value
    public V get(K k){
        return linkedHashMap.get(k);
    }
}
